#!/bin/bash

# Copyright 2019-2024 NXP
#
# SPDX-License-Identifier: BSD-3-Clause
#
# Shengzhou Liu <shengzhou.liu@nxp.com>

# Runtime Dynamic Configuration for single distro image on various NXP i.MX/Layerscape platforms.

set -e

file=/proc/device-tree/model

if grep -iq mx8mp $file; then
   soc=imx8mp
elif grep -iq mx8mm $file; then
    soc=imx8mm
elif grep -iq mx8mn $file; then
    soc=imx8mn
elif grep -iq mx8mq $file; then
    soc=imx8mq
elif grep -iq mx8qm $file; then
    soc=imx8qm
elif grep -iq mx8qxp $file; then
    soc=imx8qxp
elif grep -iq mx8ulp $file; then
    soc=imx8ulp
elif grep -iq mx91 $file; then
    soc=imx91
elif grep -iq mx93 $file; then
    soc=imx93
elif grep -iq ls1012 $file; then
    soc=ls1012a
elif grep -iq ls1028 $file; then
    soc=ls1028a
elif grep -iq ls1043 $file; then
    soc=ls1043a
elif grep -iq ls1046 $file; then
    soc=ls1046a
elif grep -iq ls1088 $file; then
    soc=ls1088a
elif grep -iq ls2088 $file; then
    soc=ls2088a
elif grep -iq lx2160 $file; then
    soc=lx2160a
else
    soc=unknown
fi

if [ $soc = imx91 -o $soc = imx93 ]; then
    if grep -qi 'Debian Desktop' /etc/issue; then
	#desktop=weston in 25Q2
	desktop=gnome
    else
	desktop=none
    fi
else
    desktop=gnome
fi

if grep -iq evk $file; then
   brd=evk
elif grep -iq frdm $file; then
    brd=frdm
elif grep -iq frwy $file; then
    brd=frwy
elif grep -iq mek $file; then
    brd=mek
elif grep -iqE 'qsb|Quick Start Board' $file; then
    brd=qsb
elif grep -iq rdb $file; then
    brd=rdb
elif grep -iq qds $file; then
    brd=qds
fi

[ $soc = unknown ] && plat=localhost || plat=${soc}${brd}

echo $plat > /etc/hostname

if [ $soc != imx8mp ]; then
    rm -f /etc/systemd/system/multi-user.target.wants/imx8-isp.service
fi

# vpu hantro daemon
if [ $soc = imx8mp ]; then
    ln -sf vsidaemon-IMX8MP /usr/bin/vsidaemon
    rm -f /etc/systemd/system/multi-user.target.wants/firmwared.service
elif [ $soc = imx8mq ]; then
    ln -sf vsidaemon-IMX8MQ /usr/bin/vsidaemon
elif [ $soc = imx8mm ]; then
    ln -sf vsidaemon-IMX8MM /usr/bin/vsidaemon
    ln -sf libg2d-viv-mx8mm.so.2.2.0 /usr/lib/libg2d.so.2
elif [ $soc = imx93 ]; then
    ln -sf libg2d-pxp.so.2.2.0 /usr/lib/libg2d.so.2
fi

if [ $soc = imx8qm -o $soc = imx8qxp ] && [ ! -L /lib/firmware/vpu ]; then
    ln -sf imx/vpu /lib/firmware/vpu
fi

if [ $desktop = gnome ] && [ $soc = imx91 -o $soc = imx93 ] && [ -f /usr/lib/libGLESv2.so ]; then
    rm -f /usr/lib/{libGLESv2.so*,libEGL.so*,libcogl.so*,libgstallocators-1.0.so,libvulkan.so}
    rm -f /usr/lib/{libdrm.so*,libgbm.so*,libgbm_viv.so}
    rm -f /usr/lib/libclutter-gst-3.0.so*
fi

# fmc service only for DPAA on ls1043/ls1046
if [ $soc != ls1043a -a $soc != ls1046a ]; then
    rm -f /etc/systemd/system/multi-user.target.wants/fmc.service
fi
